package com.neusoft.resturant.controller;

import com.neusoft.resturant.common.exception.BizException;
import com.neusoft.resturant.common.utils.Constant;
import com.neusoft.resturant.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {
    @Value("${resturant.profile}")
    private String UPLOAD_FOLDER;


    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws BizException {
        if (file.isEmpty()) {
            return R.error("上传文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(UPLOAD_FOLDER + "/" + fileName);
        try {
            file.transferTo(dest);
            String url = Constant.RESOURCE_PREFIX + "/" + fileName;
            return R.success("文件上传成功").put("url", url);
        } catch (IOException e) {
            throw new BizException(500, "文件上传失败");
        }
    }
}
